package com.cmnit.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.log4j.Logger;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/*
	1. 声明静态数据源成员变量
	2. 创建连接池对象
	3. 定义公有的得到数据源的方法
	4. 定义得到连接对象的方法
	5. 定义关闭资源的方法
 */
public class JDBCUtils {

    // 1.声明静态数据源成员变量
    private static DataSource dataSource;
    private static final Logger log = Logger.getLogger(JDBCUtils.class);

    // 2.创建连接池对象
    static {
        // 加载配置文件中的数据
        Properties prop = new Properties();
        prop.setProperty("driverClassName", ConfigurationManager.getProperty("driverClassName"));
        prop.setProperty("url", ConfigurationManager.getProperty("url"));
        prop.setProperty("username", ConfigurationManager.getProperty("username"));
        prop.setProperty("password", ConfigurationManager.getProperty("password"));
        prop.setProperty("initialSize", ConfigurationManager.getProperty("initialSize"));
        prop.setProperty("maxActive", ConfigurationManager.getProperty("maxActive"));
        prop.setProperty("minIdle", ConfigurationManager.getProperty("minIdle"));
        prop.setProperty("maxWait", ConfigurationManager.getProperty("maxWait"));
        try {
            // 创建连接池，使用配置文件中的参数
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (IOException e) {
            log.error("创建连接池打开配置文件有误：" + e.getMessage());
        } catch (Exception e) {
            log.error("创建连接池有误：" + e.getMessage());
        }
    }

    // 3.定义公有的得到数据源的方法
    public static DataSource getDataSource() {
        return dataSource;
    }

    // 4.定义得到连接对象的方法
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            log.error("获取连接对象有误：" + e.getMessage());
        }
        return conn;
    }

    // 5.定义关闭资源的方法
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.error("关闭ResultSet有误：" + e.getMessage());
            }
        }

        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.error("关闭Statement有误：" + e.getMessage());
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("关闭Connection有误：" + e.getMessage());
            }
        }
    }

    // 6.重载关闭方法
    public static void close(Connection conn, Statement stmt) {
        close(conn, stmt, null);
    }
}
